package fr.mma.livraison;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;

import fr.mma.livraison.controler.AdminDao;
import fr.mma.livraison.controler.Factory;
import fr.mma.livraison.controler.MainController;
import fr.mma.livraison.model.Developpeur;
import fr.mma.livraison.model.DeveloppeurDTO;

@SuppressWarnings("serial")
public class DevServlet extends HttpServlet {
	private AdminDao dao = new AdminDao();
	
	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		resp.setContentType("application/json");
		req.getParameter("name");
		MainController mainController =  new MainController();
		Developpeur dev = mainController.getDevByName(req.getParameter("name"));
		Gson gson = new Gson();
		String json = gson.toJson(Factory.build(dev));  
		resp.getWriter().println(json);
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		Gson gson = new Gson();
		if(req.getUserPrincipal() != null && dao.isAdmin(req.getUserPrincipal().getName())) {
			DeveloppeurDTO request = gson.fromJson(req.getParameter("request"), DeveloppeurDTO.class);
			MainController mainController =  new MainController();
			mainController.save(request);
			resp.setContentType("application/json");
			resp.getWriter().println(gson.toJson(new String("ok")));
		} else {
			resp.getWriter().println(gson.toJson("ko"));
		}
		
	}
}
